<?php
/**
 * Author: MeiJay
 * Date: 2020/3/10 12:13
 * Time: 9:44
 * Desc:
 */


namespace App\Admin\Forms\PurchaseOrder;


use App\Admin\Services\PurchaseService;
use App\Model\Good;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class Import extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '订货单导入';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     * @throws IOException
     * @throws ReaderNotOpenedException
     */
    public function handle(Request $request)
    {
        $reader = ReaderEntityFactory::createCSVReader();
        $reader->open($request->file('file'));

        $sheets = $reader->getSheetIterator();
        $sheets->rewind();
        $sheet = $sheets->current();

        $import = [];
        foreach ($sheet->getRowIterator() as $k => $row) {
            if ($k == 0) {
                continue;
            }
            $rowArr = $row->toArray();

            if (empty($rowArr[0]) || empty($rowArr[1])) {
                continue;
            }

            $import[] = [
                'sku' => $rowArr[0],
                'count' => (int)$rowArr[1]
            ];

        }
        $reader->close(); // 释放内存
        $dbSku = Good::query()->whereIn('web_sku', array_column($import, 'sku'))
            ->get(['id', 'web_sku', 'supplier_id']);

        $insert = $err = [];
        foreach ($import as $sku) {
            if ($db = $dbSku->where('web_sku', $sku['sku'])->first()) {
                $sku['supplier_id'] = $db->supplier_id;
                $sku['good_id'] = $db->id;
                $insert[] = $sku;
            } else {
                $err[] = $sku['sku'];
            }
        }

        if (empty($insert)) {
            admin_toastr("未查询到有效数据", "info", ['timeOut' => 5000]);
            return back();
        }
        $successCount = (new PurchaseService())->import($insert);

        admin_toastr("表中一共" . count($import) . "个sku，成功操作" . $successCount . "个", "info", ['timeOut' => 5000]);
        return back();
    }

    /**
     * Build a form here
     */
    public function form()
    {
        $this->file('file', '请选择文件')
            ->rules('required', [
                'required' => '请选择上传文件',
                'mimes' => '请上传csv文件'
            ]);
    }

}

